<template>
  <div class="switch-container">
    <input type="checkbox" :id="id" :checked="modelValue" @change="toggleSwitch" class="switch-input" />
    <label :for="id" class="switch" :class="sizeClass" :style="switchStyle">
      <span v-if="onText || offText" class="switch-text">
        {{ modelValue ? onText : offText }}
      </span>
    </label>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits, watch, computed } from "vue"

// 接收开关的状态值和显示的文本
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  onText: {
    type: String,
    default: "Yes"
  },
  offText: {
    type: String,
    default: "No"
  },
  size: {
    type: String,
    default: "medium"
  }
})

const emit = defineEmits(["update:modelValue"])

const id = "switch-" + Math.random().toString(36).substring(7)

// 控制开关状态改变的函数
const toggleSwitch = () => {
  emit("update:modelValue", !props.modelValue)
}

// 根据大小传入不同的类名
const sizeClass = computed(() => {
  return {
    "switch-mini": props.size === "mini",
    "switch-small": props.size === "small",
    "switch-medium": props.size === "medium",
    "switch-large": props.size === "large"
  }
})

// 开关背景色和文本样式
const switchStyle = computed(() => {
  return {
    backgroundColor: props.modelValue ? "#409EFF" : "#dcdcdc", // 开启时蓝色，关闭时浅灰色
    color: props.modelValue ? "#ffffff" : "#666666" // 开启时文字为白色，关闭时文字为灰色
  }
})
</script>

<style scoped>
.switch-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.switch-input {
  display: none;
}

.switch {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px 20px;
  background-color: #dcdcdc;
  border-radius: 50px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.switch-text {
  font-size: 1em;
  font-weight: 600;
  color: inherit; /* 根据背景色变化的文字颜色 */
}

.switch svg path {
  fill: #ffffff;
  transition: all 0.3s ease;
}

.switch-mini {
  font-size: 5px;
}

.switch-small {
  font-size: 12px;
}

.switch-medium {
  font-size: 16px;
}

.switch-large {
  font-size: 20px;
}

#checkbox:checked + .switch {
  background-color: #409eff;
  box-shadow: 0 0 40px rgba(64, 158, 255, 0.4);
}
</style>
